/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mp3filter;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
/*import org.slf4j.LoggerFactory;
import org.slf4j.*;
import org.slf4j.helpers.*;
import org.slf4j.spi.*;*/
import org.slf4j.impl.*;

import org.farng.mp3.MP3File;
import org.farng.mp3.TagException;
import org.farng.mp3.id3.ID3v1;

import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
 *
 * @author gioak
 */
public class Mp3Filter {

       public static void main(String[] args) {

                       String path = args[0];
                       String filename = args[1];
                       String command = args[2];
                       try {

                       System.out.println(path);
                       System.out.println(filename);
                       //this will be unique Id used by Solr to index the file contents.
                       InetAddress ip = InetAddress.getByName("127.0.0.1");
                       String hostname = ip.getHostName();
                       String solrId = hostname + "|" + path;

                       if(command.equals("INSERT"))
                       {
                            indexFilesSolrCell(path, filename, solrId);
                       }
                       else if(command.equals("UPDATE"))
                       {

                       }
                       else if(command.equals("DELETE"))
                       {
                            deleteFilesSolrCell(solrId);
                       }

               } catch (Exception e) {
                       //se il file non viene trovato o non è disponibile
                       //System.out.println(e.toString());
                   try
     {


          String homePath = System.getenv("HOME");
          String pathFileLog = homePath + "/.mediawhere/errors.log";
          FileOutputStream fos = new FileOutputStream(pathFileLog, true);
          PrintStream ps = new PrintStream(fos);
          Calendar cal = new GregorianCalendar();
          int giorno = cal.get(Calendar.DAY_OF_MONTH);
          int mese = cal.get(Calendar.MONTH);
          int anno = cal.get(Calendar.YEAR);
          //System.out.println(giorno + "/" + (mese + 1) + "/" + anno);
          String orario;
          int ore = cal.get(Calendar.HOUR);
          int minuti = cal.get(Calendar.MINUTE);
          int secondi = cal.get(Calendar.SECOND);

          if(cal.get(Calendar.AM_PM) == 0)
          orario = "A.M.";
          else
          orario = "P.M.";
          //System.out.println("Sono le : " + ore + ":"   + minuti + ":" + secondi + " " + orario);



          ps.println("ERROR. [" + giorno + "/" + (mese+1) + "/" + anno + "]  ["+ ore + ":"   + minuti + ":" + secondi + " " + orario +"]  Indexing file [" + path + "] failed:  " );
          e.printStackTrace(ps);
          ps.println("\n\n");

      }
      catch (IOException ex)
      {
          System.out.println("Errore: " + ex);
          System.exit(1);
      }

               }

       }

       public static void indexFilesSolrCell(String pathName, String fileName, String solrId) throws IOException, SolrServerException
       {

       String urlString = "http://localhost:8983/solr";
       SolrServer solr = new CommonsHttpSolrServer(urlString);

       try
       {
           MP3File file = new MP3File(new File(pathName));
           /*ID3v1 tryTag = new ID3v1();
           tryTag.setAlbum("Prova Album");
           file.setID3v1Tag(tryTag);*/
           ID3v1 tags = file.getID3v1Tag();
           //tags.setAuthorComposer("null");


           System.out.println("Nome artista:\t"+tags.getArtist());
           System.out.println("Titolo album:\t"+tags.getAlbumTitle());
           System.out.println("Titolo canzone:\t"+tags.getSongTitle());
           System.out.println("Genere canzone:\t"+tags.getSongGenre());
           //System.out.println("Autore canzone:\t"+tags.getAuthorComposer());


       ContentStreamUpdateRequest up
         = new ContentStreamUpdateRequest("/update/extract");

       up.addFile(new File(pathName));

       up.setParam("literal.id", solrId);
       up.setParam("literal.filename", fileName);
       up.setParam("literal.artist", tags.getArtist());
       up.setParam("literal.albumTitle", tags.getAlbumTitle());
       up.setParam("literal.songTitle", tags.getSongTitle());
       up.setParam("literal.songGenre", tags.getSongGenre());
       //up.setParam("literal.authorComposer", tags.getAuthorComposer());
       up.setParam("uprefix", "attr_");

       //up.setParam("fmap.content", "attr_content");

       //Sets appropriate parameters for the given ACTION
       //setAction(AbstractUpdateRequest.ACTION action,boolean waitFlush, boolean waitSearcher)
       up.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);

       solr.request(up);

       QueryResponse rsp = solr.query(new SolrQuery(fileName));

       System.out.println(rsp);
       }
                    catch (TagException e) {
                       //se uno dei tag richiesti non è presente
                       e.printStackTrace();
           }
        }


         public static void deleteFilesSolrCell(String solrId)
    {
        String home = System.getenv("HOME");
        System.out.println(home);
        File wd = new File(home + "/.mediawhere/found/");
        System.out.println(wd);
        Process proc = null;
        try {
           proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
        }
        catch (IOException e) {
           e.printStackTrace();
           return;
        }
        if (proc != null) {
           BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
           PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
           //out.println("cd /home/kinder/apache-solr-1.4.1/example/exampledocs/");
           out.println("java -Ddata=args -Dcommit=yes -jar post.jar " + "\"<delete><id>" + solrId + "</id></delete>\"");
           out.println("exit");
           //out.println("java -jar post.jar");
           try {
              String line;
              while ((line = in.readLine()) != null) {
                 System.out.println(line);
              }
              proc.waitFor();
              in.close();
              out.close();
              proc.destroy();
           }
           catch (Exception e) {
              e.printStackTrace();
           }
        }
    }
}


